package authentication;

import java.io.*;
import java.util.logging.Logger;



import exception.UserPermissionException;


public class UserAuthentication implements AuthenticationInterface{
    public Encrypter _encrypter;
    public File _users_file;
    private Logger logger = Logger.getLogger("AuthenticationLog.txt");
    public UserAuthentication(String path){
    	_users_file = new File(path);
        _encrypter = new Encrypter();
    }

    private boolean isUserLine(String enc_user, String enc_pw, String line){
        String line_user, line_pw;
        int i = line.indexOf(" ; ");
        line_user = line.substring(0, i);
        line_pw = line.substring(i+3);
        return enc_user.equals(line_user) & line_pw.startsWith(enc_pw+" ; ");
    }

    public boolean containsUser(String un) {
         String username = _encrypter.encrypt(un);
        boolean exist = false;
        try {
            FileInputStream  fis = new FileInputStream( _users_file );
            DataInputStream dis = new DataInputStream(fis);
            BufferedReader br = new BufferedReader(new InputStreamReader(dis));
            String line = "";
            while ((line = br.readLine()) != null && !exist){
                exist = line.startsWith(username + " ; ");
            }
            dis.close();
        } catch (Exception e){
        }
        return exist;
    }

    public boolean checkUser(String un, String pw){
         boolean exist = false;
         String username = _encrypter.encrypt(un);
         String password = _encrypter.encrypt(pw);
        try {
            FileInputStream  fis = new FileInputStream( _users_file );
            DataInputStream dis = new DataInputStream(fis);
            BufferedReader br = new BufferedReader(new InputStreamReader(dis));
            String line = "";
            while ((line = br.readLine()) != null && !exist){
                exist = isUserLine(username,password,line);
            }
            dis.close();
        } catch (Exception e){
            System.out.println(e.getMessage());
        }
  //       if (!exist) System.out.print("user doesnt exist\n");
        return exist;
    }

    public boolean addUser(String un, String pw,String permission) throws Exception{
        boolean exist = containsUser(un);
        if (exist){
         return false;
         //   throw new Exception("can not add user - username \""+un+"\" already in use");
        }
        String username = _encrypter.encrypt(un);
        String password = _encrypter.encrypt(pw);
        FileWriter fw = new FileWriter(_users_file, true);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.append(username + " ; " + password + " ; "+ permission + "\n");
        bw.close();
        return true;
    }

    public boolean deleteUser(String un){
        String username = _encrypter.encrypt(un);
        String fileStr = "";
        boolean found = false;
        try {
            FileInputStream  fis = new FileInputStream( _users_file );
            DataInputStream dis = new DataInputStream(fis);
            BufferedReader br = new BufferedReader(new InputStreamReader(dis));
            String line;
            while ((line = br.readLine()) != null){
                if ( !line.startsWith(username+" ")){
                    fileStr+=line + "\n";
                }
                else {
                    found = true;
                }
            }
            dis.close();
            
        } catch (Exception e){
            System.out.println(e.getMessage());
        }
        if (!found) return false;
        try {
            _users_file.createNewFile();
            FileWriter fw = new FileWriter(_users_file);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(fileStr);
            bw.close();
        } catch (IOException ex) {
        }
        return true;
    }

    public String getUserPermission(String un){
        String username = _encrypter.encrypt(un);
        String perm = null;
        String line = "";
        try {
            FileInputStream  fis = new FileInputStream( _users_file );
            DataInputStream dis = new DataInputStream(fis);
            BufferedReader br = new BufferedReader(new InputStreamReader(dis));
            while ((line = br.readLine()) != null && perm == null){
            	if (line.startsWith(username + " ; ")){
                    if (line.endsWith("MEMBER")) return "MEMBER";
                    if (line.endsWith("ADMIN")) return "ADMIN";
                    throw new UserPermissionException();
                }
            }
            dis.close();
        } catch (UserPermissionException e){
            logger.info("No such permission: " + (line.substring(line.lastIndexOf("; ")+2)));
        }
        catch (Exception e1){}
        return perm;
    }
}